<template>
  <div :class="{'cantEdit':!isEdit}">
    <el-upload
      class="upload-demo"
      action="http://macro-oss.oss-cn-shenzhen.aliyuncs.com"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload"
      multiple
      :limit="maxCount"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :disabled="!isEdit"
    >
      <el-button v-if="isEdit" size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">{{ isEdit? hint : '点击可下载发票文件' }}</div>
    </el-upload>
  </div>
</template>
<script>
// import { ossUpload } from '@/api/oss'

export default {
  name: 'FileUpload',
  props: {
    // 图片属性数组
    value: {
      type: String,
      default: ''
    },
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 1
    },
    // 提示
    hint: {
      type: String,
      default: ''
    },
    // 是否可编辑
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {}
  },
  computed: {
    imageUrl() {
      return this.value
    },
    imageName() {
      if (this.value !== null && this.value !== '') {
        return this.value.substr(this.value.lastIndexOf('/') + 1)
      } else {
        return null
      }
    },
    fileList() {
      if (
        this.value !== undefined &&
        this.value !== '' &&
        this.value.length !== 0
      ) {
        return [
          {
            name: this.imageName,
            url: this.imageUrl
          }
        ]
      } else {
        return []
      }
    }
  },
  methods: {
    emitInput(url) {
      this.$emit('input', url)
    },
    handleRemove(file, fileList) {
      this.emitInput('')
    },
    handlePreview(file) {
      const a = document.createElement('a')
      a.href = this.value
      a.click()
    },
    beforeUpload(file) {
      console.log(file)
      var fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'pdf') {
        this.$message({
          message: '只能上传格式为pfd格式的文件！此文件格式为' + fileType,
          type: 'error',
          duration: 3000
        })
        return false
      }
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        url: 'http://www.jcd' + '/' + file.name
      })
      this.emitInput(this.fileList[0].url)
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '个文件',
        type: 'warning',
        duration: 3000
      })
    }
  }
}
</script>
<style scoped>
.cantEdit >>> .el-upload {
  display: block;
}
.cantEdit a {
  outline: none;
}
</style>

